public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null){
            return head;
        }
        if(k == 0){
            return head;
        }
        ListNode pos = head.next;
        ListNode pos1 = head;
        int len = 0;
        while(pos != null){
            pos1 = pos;
            pos = pos.next;
            len++;
        }
        len = len+1;
        if(k == len){
            return head;
        }
        pos1.next = head;
        int count = k % len;
        int n = len - count;
        ListNode cur = head;
        ListNode prev = null;
        while(n != 0){
            prev = cur;
            cur = cur.next;
            n--;
        }
        head = cur;
        prev.next = null;
        return head;
    }
}